<template>
  <div class="pplan-management-container">
    <el-card class="operate-container" shadow="never">
      <el-button type="primary" :icon="Plus" @click="handleCreate">创建生产计划</el-button>
    </el-card>

    <el-card class="table-container" shadow="never">
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="pplanSheet" label="任务单号" width="180" />
        <el-table-column prop="pid" label="产品ID" />
        <el-table-column prop="amount" label="数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
                type="primary"
                :icon="Cpu"
                @click="handleGenerate(scope.row.pplanSheet)"
                :disabled="generatedSheetIds.has(scope.row.pplanSheet)"
            >
              {{ generatedSheetIds.has(scope.row.pplanSheet) ? '已生成' : '生成计划' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          class="pagination-container"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.size"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <plan-editor v-model:visible="dialogVisible" @success="handleSuccess" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Cpu } from '@element-plus/icons-vue'
import { getPplanPage, generatePieces, getGeneratedPplanSheetIds } from '@/api/modules/pplan'
import PlanEditor from './components/PlanEditor.vue'

const loading = ref(true)
const tableData = ref([])
const total = ref(0)
const queryParams = reactive({ current: 1, size: 10 })
const dialogVisible = ref(false)
const generatedSheetIds = ref(new Set())

const fetchGeneratedIds = async () => {
  try {
    const ids = await getGeneratedPplanSheetIds();
    generatedSheetIds.value = new Set(ids);
  } catch (error) {
    console.error("获取已生成ID列表失败", error);
  }
}

const fetchPplanList = async () => {
  loading.value = true
  try {
    await Promise.all([
      getPplanPage(queryParams).then(data => {
        tableData.value = data.records;
        total.value = data.total;
      }),
      fetchGeneratedIds()
    ]);
  } catch (error) {
    console.error('获取生产计划列表失败', error)
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size) => { queryParams.size = size; fetchPplanList(); }
const handleCurrentChange = (current) => { queryParams.current = current; fetchPplanList(); }
const handleCreate = () => { dialogVisible.value = true; }
const handleSuccess = () => { fetchPplanList(); }

const handleGenerate = (pplanSheetId) => {
  ElMessageBox.confirm(`确定要为任务单 ${pplanSheetId} 生成计划吗？`, '提示', { type: 'info' })
      .then(async () => {
        try {
          await generatePieces(pplanSheetId)
          ElMessage.success('工件生成成功')
          generatedSheetIds.value.add(pplanSheetId)
        } catch (error) {
          console.error('生成工件失败', error)
        }
      }).catch(() => {})
}

onMounted(() => { fetchPplanList() })
</script>

<style scoped>
.pplan-management-container { padding: 20px; }
.operate-container { margin-bottom: 20px; }
.pagination-container { margin-top: 20px; display: flex; justify-content: flex-end; }
</style>
